package org.dromara.bykt.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dromara.bykt.domain.vo.BYKTCourseQuestionsImportVo;
import org.dromara.bykt.domain.vo.BYKTCourseSimulationImportVo;
import org.dromara.bykt.listener.BYKTCourseQuestionsImportListener;
import org.dromara.bykt.listener.BYKTCourseSimulationImportListener;
import org.dromara.bykt.utils.AliOSSUpload;
import org.dromara.bykt.utils.ByteArrayMultipartFile;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.excel.core.ExcelResult;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.bykt.domain.vo.BYKTCourseSimulationVo;
import org.dromara.bykt.domain.bo.BYKTCourseSimulationBo;
import org.dromara.bykt.service.IBYKTCourseSimulationService;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 模拟卷
 *
 * @author Hou
 * @date 2025-06-22
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/bykt/simulation")
public class BYKTCourseSimulationController extends BaseController {

    private final IBYKTCourseSimulationService courseSimulationService;

    /**
     * 查询模拟卷列表
     */
    @GetMapping("/list")
    public TableDataInfo<BYKTCourseSimulationVo> list(BYKTCourseSimulationBo bo, PageQuery pageQuery) {
        return courseSimulationService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出模拟卷列表
     */
    @Log(title = "模拟卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
//        List<BYKTCourseSimulationVo> list = courseSimulationService.queryList(bo);
        ExcelUtil.exportExcel(null, "模拟卷", BYKTCourseSimulationVo.class, response);
    }

    /**
     * 获取模拟卷详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<BYKTCourseSimulationVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(courseSimulationService.queryById(id));
    }

    /**
     * 新增模拟卷
     */
    @Log(title = "模拟卷", businessType = BusinessType.INSERT)
    @PostMapping()
    public R<Void> add(@RequestBody BYKTCourseSimulationBo bo) {
        return toAjax(courseSimulationService.insertByBo(bo));
    }

    /**
     * 修改模拟卷
     */
    @Log(title = "模拟卷", businessType = BusinessType.UPDATE)
    @PutMapping()
    public R<Void> edit(@RequestBody BYKTCourseSimulationBo bo) {
        return toAjax(courseSimulationService.updateByBo(bo));
    }

    /**
     * 删除模拟卷
     *
     * @param ids 主键串
     */
    @Log(title = "模拟卷", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(courseSimulationService.deleteWithValidByIds(List.of(ids), true));
    }

    @Log(title = "题目管理导入", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/courseSimulationImportData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> courseSimulationImportData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        // 1. 读取Excel文件
        Workbook workbook = new XSSFWorkbook(file.getInputStream());

        // 2. 获取所有图片数据并上传到OSS
        Map<String, String> pictureMap = processExcelImages(workbook);

        // 3. 创建自定义监听器并导入数据
        BYKTCourseSimulationImportListener listener = new BYKTCourseSimulationImportListener(updateSupport, pictureMap);
        ExcelResult<BYKTCourseSimulationImportVo> result = ExcelUtil.importExcel(
            file.getInputStream(),
            BYKTCourseSimulationImportVo.class,
            listener
        );

        return R.ok(result.getAnalysis());
    }

    // 处理Excel中的图片并上传到OSS
    private Map<String, String> processExcelImages(Workbook workbook) throws Exception {
        Map<String, String> pictureMap = new HashMap<>();
        List<? extends PictureData> pictures = workbook.getAllPictures();
        AliOSSUpload ossUpload = SpringUtils.getBean(AliOSSUpload.class); // 使用SpringUtils获取Bean

        for (int i = 0; i < pictures.size(); i++) {
            PictureData picture = pictures.get(i);
            byte[] data = picture.getData();
            String ext = picture.suggestFileExtension();
            String fileName = System.currentTimeMillis() + "_" + i + ".jpg";

            // 创建临时MultipartFile
            MultipartFile multipartFile = new ByteArrayMultipartFile(
                data,
                fileName,
                fileName,
                "image/" + ext
            );

            // 上传到OSS
            String ossUrl = ossUpload.uploadImage(multipartFile);
            pictureMap.put("picture_" + i, ossUrl); // 使用图片ID作为key
        }

        return pictureMap;
    }
}
